<?php
/*                            _ooOoo_
 *                           o8888888o
 *                           88" . "88
 *                           (| -_- |)
 *                            O\ = /O
 *                        ____/`---'\____
 *                      .   ' \\| |// `.
 *                       / \\||| : |||// \
 *                     / _||||| -:- |||||- \
 *                       | | \\\ - /// | |
 *                     | \_| ''\---/'' | |
 *                      \ .-\__ `-` ___/-. /
 *                   ___`. .' /--.--\ `. . __
 *                ."" '< `.___\_<|>_/___.' >'"".
 *               | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *                 \ \ `-. \_ __\ /__ _/ .-` / /
 *         ======`-.____`-.___\_____/___.-`____.-'======
 *                            `=---='
 *
 *         .............................................
 *                  佛祖保佑             永无BUG
 *
 * ======================================================
 * @author: Ethan Lu <ethan.lu@qq.com>
 * 
 */

namespace front\modules\web\controllers;


use order\models\Orders;
use order\services\OrderService;
use Overtrue\Wechat\Utils\XML;
use Yii;
use Overtrue\Wechat\Payment;
use Overtrue\Wechat\Payment\Notify;
use yii\web\Controller;

use EasyWeChat\Foundation\Application;

class PayController extends Controller
{

    private $_appId = '';
    private $_appSecret = '';
    private $_mch_id = '';
    private $_mch_key = '';

    public function init()
    {
        \Yii::$app->request->enableCsrfValidation = false;
    }


    public function actionNotify_3()
    {
        $_appId = 'wxb92c2bb9c487c950';
        $_mch_id = '1301495501';
        $_mch_key = 'Yk3Bn8sBsg2yJ83gfkKHgfehe7Hdggsk';
        $options = [
            'app_id' => $_appId,
            'payment' => [
                'merchant_id'        => $_mch_id,
                'key'                => $_mch_key,
            ],
        ];

        $app = new Application($options);
        $response = $app->payment->handleNotify(function($notify, $successful){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = Orders::findOne(['order_id' => $notify->out_trade_no]);

            if (!$order) { // 如果订单不存在
                return 'Order not exist.'; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            $data = [];
            array_push($data,[
                'order_id' => $notify->out_trade_no,
                'cost' => $notify->cash_fee / 100,
                'payment_type' => 1,
            ]);
            $result = OrderService::payOrder($data);
            \Yii::info($result, "**********************************");
            if ($result['code'] != 0) {
                return '暂时无法更新订单状态~';
            }
            return true; // 或者错误消息
        });

        echo $response->send();//return $response;// 或者 $response->send()
    }
}